package com.iflytek.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import com.github.pagehelper.Page;
import com.iflytek.bean.Book;
import com.iflytek.service.BookService;

@Controller
@RequestMapping("/book")
public class BookController {
	
	@Autowired
	private BookService bookService;

	@GetMapping("/list")
	public String listBook(@RequestParam(defaultValue = "1") Integer pageNum,
			@RequestParam(defaultValue = "5") Integer pageSize,  Model model) {
		Page<Book> bookList = bookService.getBooksByPage(pageNum,pageSize);
		model.addAttribute("bookList", bookList.getResult());
		model.addAttribute("page", bookList.toPageInfo());
		return "book/list";
	}
	
	@GetMapping("/detail")
	public String bookDetail(Integer id, Model model) {
		Book book = bookService.findBookById(id);
		model.addAttribute("book", book);
		return "book/detail";
	}
	
	@GetMapping("/add")
	public String addBook() {
		return "book/add";
	}
	
	@PostMapping("/save")
	public String saveBook(Book book) {
		book.setStock(book.getTotalStock());  //初始时在馆数量等于总数量
		bookService.saveBook(book);
		return "redirect:/book/list";
	}
	
	@GetMapping("/edit")
	public String editBook(Integer id, Model model) {
		Book book = bookService.findBookById(id);
		model.addAttribute("book", book);
		return "book/edit";
	}
	
	@PostMapping("/update")
	public String updateBook(Book book) {
		bookService.updateBook(book);
		return "redirect:/book/list";
	}
	
	@GetMapping("/del")
	public String deleteBook(Integer id) {
		bookService.deleteBook(id);
		return "redirect:/book/list";
	}

}
